import axios from 'axios';
import { Post, Comment } from '../types';
import { API_PATHS, getAuthHeaders } from '../../../config/apiConfig';
import { CommentService } from './CommentService';
import { AuthService } from '../../auth/services/AuthService';

export class PostService {
  private static readonly API_BASE = API_PATHS.posts;

  // 将后端返回的数据转换为前端需要的格式
  private static transformPost(post: any): Post {
    console.log('转换前的帖子数据:', post);
    
    // 正确处理用户名和用户ID，考虑嵌套结构
    let userId = 0;
    let username = '未知用户';
    
    // 检查是否有user对象
    if (post.user) {
      userId = post.user.userId || 0;
      username = post.user.username || '未知用户';
    } else {
      // 兼容直接在帖子对象上的userId和username
      userId = post.userId || 0;
      username = post.username || '未知用户';
    }
    
    const transformedPost = {
      postId: post.postId,
      user: {
        userId: userId,
        username: username
      },
      postTitle: post.postTitle || '',
      postContent: post.postContent || post.content || '',
      postTime: post.postTime || new Date().toISOString(),
      commentCount: post.commentCount || (post.comments ? post.comments.length : 0)
    };
    console.log('转换后的帖子数据:', transformedPost);
    return transformedPost;
  }

  // 创建帖子
  static async createPost(postContent: string, postTitle: string): Promise<Post> {
    // 获取当前用户信息
    const currentUser = AuthService.getCurrentUser();
    if (!currentUser) {
      throw new Error('用户未登录');
    }
    
    const response = await axios.post(
      this.API_BASE,
      { 
        user: {
          userId: Number(currentUser.id),
          username: currentUser.username // 添加username字段
        },
        postContent,
        postTitle
      },
      { headers: getAuthHeaders() }
    );
    return this.transformPost(response.data);
  }

  // 通过ID查询帖子
  static async getPostById(postId: number): Promise<Post> {
    try {
      // 确保 postId 是数字类型
      const postIdNumber = Number(postId);
      if (isNaN(postIdNumber)) {
        console.error('无效的帖子ID:', postId);
        throw new Error('无效的帖子ID');
      }
      
      console.log(`正在获取帖子ID为${postIdNumber}的详情，API路径: ${this.API_BASE}/${postIdNumber}`);
      const response = await axios.get(
        `${this.API_BASE}/${postIdNumber}`,
        { headers: getAuthHeaders() }
      );
      
      // 获取帖子的评论数据
      const comments = await CommentService.getCommentsByPostId(postIdNumber);
      
      // 转换帖子数据并添加评论
      const post = this.transformPost(response.data);
      post.comments = comments;
      post.commentCount = comments.length;
      
      console.log('获取帖子成功，包含评论数据');
      return post;
    } catch (error) {
      console.error('获取帖子详情失败:', error);
      throw error;
    }
  }

  // 通过用户ID查询帖子
  static async getPostsByUserId(userId: number): Promise<Post[]> {
    try {
      // 确保 userId 是数字类型
      const userIdNumber = Number(userId);
      if (isNaN(userIdNumber)) {
        console.error('无效的用户ID:', userId);
        throw new Error('无效的用户ID');
      }
      
      console.log(`正在获取用户ID为${userIdNumber}的帖子列表，API路径: ${this.API_BASE}/user/${userIdNumber}/with-comments`);
      const response = await axios.get(
        `${this.API_BASE}/user/${userIdNumber}/with-comments`,
        { headers: getAuthHeaders() }
      );
      
      // 直接返回转换后的帖子数据
      console.log('获取用户帖子成功');
      return response.data.map((post: any) => this.transformPost(post));
    } catch (error) {
      console.error('获取用户帖子列表失败:', error);
      throw error;
    }
  }

  // 获取所有帖子
  static async getAllPosts(): Promise<Post[]> {
    try {
      console.log(`正在获取所有帖子，API路径: ${this.API_BASE}`);
      const headers = getAuthHeaders();
      console.log('请求头信息:', headers);
      
      const response = await axios.get(
        this.API_BASE,
        { headers }
      );
      if (!Array.isArray(response.data)) {
        throw new Error('后端返回的数据不是数组');
      }
      
      console.log('获取帖子响应状态:', response.status);
      console.log('获取帖子响应数据:', response.data);
      
      // 处理后端返回的帖子数据
      const postsData = response.data || [];
      
      // 直接返回转换后的帖子数据
      console.log('获取所有帖子成功');
      return postsData.map((post: any) => this.transformPost(post));
    } catch (error) {
      console.error('获取所有帖子失败:', error);
      if (axios.isAxiosError(error)) {
        console.error('请求错误详情:', {
          status: error.response?.status,
          statusText: error.response?.statusText,
          data: error.response?.data,
          headers: error.response?.headers
        });
      }
      throw error;
    }
  }

  // 更新帖子
  static async updatePost(postId: number, postContent: string, postTitle?: string): Promise<Post> {
    // 获取当前用户信息
    const currentUser = AuthService.getCurrentUser();
    if (!currentUser) {
      throw new Error('用户未登录');
    }
    
    // 构建符合后端API要求的请求体
    const postData = {
      user: {
        userId: Number(currentUser.id),
        username: currentUser.username // 添加username字段
      },
      postId: postId,
      postContent: postContent,
      // 如果提供了标题则包含标题，否则不包含
      ...(postTitle && { postTitle })
    };
    
    console.log('更新帖子请求数据:', postData);
    
    const response = await axios.put(
      this.API_BASE,
      postData,
      { headers: getAuthHeaders() }
    );
    return this.transformPost(response.data);
  }

  // 删除帖子
  static async deletePost(postId: number): Promise<void> {
    await axios.delete(
      `${this.API_BASE}/${postId}`,
      { headers: getAuthHeaders() }
    );
  }
}